@using Unity.ClusterDisplay.MissionControl.EngineeringUI.Services
@using Unity.ClusterDisplay.MissionControl.MissionControl

@inject MissionControlStatusService MissionControlStatusService
@inject MissionCommandsService MissionCommandsService
@inject LaunchConfigurationService LaunchConfigurationService
@inject AssetsService AssetsService;

@implements IDisposable

<RadzenStack AlignItems="AlignItems.Center" JustifyContent="JustifyContent.End" Orientation="Orientation.Horizontal">
    <RadzenText Text="@SelectedAsset" Style="font-weight: bold"/>

    @if (MissionControlStatusService.State is State.Idle)
    {
        <RadzenButton Text="Launch" ButtonStyle="ButtonStyle.Info" Icon="play_arrow"
                      Click="@MissionCommandsService.LaunchMissionAsync"
                      Disabled=@(LaunchConfigurationService.WorkValue.AssetId == Guid.Empty)/>
    }
    else
    {
        <RadzenButton Text="Stop" ButtonStyle="ButtonStyle.Light" Icon="stop"
                      Click="@(MissionCommandsService.StopCurrentMissionAsync)"/>
    }

</RadzenStack>

@code {
    string? SelectedAsset => AssetsService.Collection.TryGetValue(
        LaunchConfigurationService.WorkValue.AssetId, out var asset)
        ? $"Selected asset: {asset.Name}"
        : null;

    protected override void OnInitialized()
    {
        base.OnInitialized();
        MissionControlStatusService.ObjectChanged += MissionStatusChanged;
        LaunchConfigurationService.WorkValue.ObjectChanged += OnSelectedAssetChanged;
        AssetsService.Collection.SomethingChanged += OnAssetCollectionChanged;
    }

    void MissionStatusChanged(ObservableObject obj)
    {
        StateHasChanged();
    }

    void OnAssetCollectionChanged(IReadOnlyIncrementalCollection obj)
    {
        StateHasChanged();
    }

    void OnSelectedAssetChanged(ObservableObject _)
    {
        StateHasChanged();
    }

    public void Dispose()
    {
        MissionControlStatusService.ObjectChanged -= MissionStatusChanged;
        LaunchConfigurationService.WorkValue.ObjectChanged -= OnSelectedAssetChanged;
        AssetsService.Collection.SomethingChanged -= OnAssetCollectionChanged;
    }

}
